package cn.tedu.store.admin.webapi.service.impl;


import cn.tedu.store.admin.webapi.mapper.PermissionMapper;
import cn.tedu.store.commons.ex.ServiceException;
import cn.tedu.store.commons.pojo.admin.dto.PermissionAddNewDTO;
import cn.tedu.store.commons.pojo.admin.entity.Permission;
import cn.tedu.store.commons.pojo.admin.vo.PermissionListItemVO;
import cn.tedu.store.commons.pojo.admin.vo.PermissionStandardVO;
import cn.tedu.store.commons.web.ServiceCode;
import cn.tedu.store.admin.service.IPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public void addNew(PermissionAddNewDTO permissionAddNewDTO) {
        int count = permissionMapper.countByName(permissionAddNewDTO.getName());
        if (count != 0) {
            String message = "添加角色失败,该角色已存在!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionAddNewDTO, permission);
        permissionMapper.insert(permission);
        log.debug("添加管理员成功!");
    }

    @Override
    public void delete(Long id) {
        int count = permissionMapper.countById(id);
        if (count == 0) {
            String message = "删除权限失败,该权限不存在!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        permissionMapper.deleteById(id);
        log.debug("删除权限成功!");
    }

    @Override
    public void updateById(Long id, PermissionAddNewDTO permissionAddNewDTO) {
        log.debug("即将处理修改角色业务!");
        PermissionStandardVO permissionStandardVO = permissionMapper.getStandardById(id);
        if (permissionStandardVO == null) {
            String message = "修改权限失败,该权限不存在!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionAddNewDTO, permission);
        permission.setId(id);
        log.debug("即将修改的数据: {}", permission);
        int count = permissionMapper.updateById(permission);
        if (count != 1){
            String message = "修改权限失败,服务器忙,请稍后重试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }

    }

    @Override
    public List<PermissionListItemVO> list() {
        log.debug("开始处理查询角色列表业务!");
        return permissionMapper.list();
    }
}
